package com.lu.project.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.ssh.JschUtil;


import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;

import com.lu.project.common.BaseResponse;
import com.lu.project.common.PageResponse;
import com.lu.project.common.ResultUtils;
import com.lu.project.constant.Constants;
import com.lu.project.model.dto.device.DeviceDataDto;
import com.lu.project.model.entity.Device;
import com.lu.project.model.entity.DeviceData;
import com.lu.project.model.vo.DeviceDataVo;
import com.lu.project.service.DeviceDataService;
import com.lu.project.service.DeviceService;
import com.lu.project.websocket.WebSocketData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;


import java.util.List;

import static com.lu.project.constant.Constants.DEVICE_LASTDATA_CACHE_KEY;

@RestController
@RequestMapping("/device-data")
@Api(tags = "设备数据管理接口")
public class DeviceDataController {

    @Resource
    private DeviceDataService deviceDataService;

    @Resource
    private DeviceService deviceService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @PostMapping("/create")
    @ApiOperation(value = "创建设备数据", notes = "接收一个DeviceDataDto对象作为请求参数，返回void")
    public BaseResponse createDeviceData(@RequestBody @ApiParam(value = "设备数据", required = true) DeviceDataDto deviceDataDto) {
        deviceDataService.createDeviceData(deviceDataDto);
        return ResultUtils.success(true);
    }

    @GetMapping("/read/{id}")
    @ApiOperation(value = "读取设备数据", notes = "接收一个id参数作为请求参数，返回一个DeviceDataVo对象")
    public BaseResponse<DeviceDataVo> readDeviceData(@PathVariable @ApiParam(value = "设备数据ID", required = true) Long id) {
        return ResultUtils.success(deviceDataService.readDeviceData(id));
    }

    @PutMapping("/update/{id}")
    @ApiOperation(value = "处理", notes = "接收一个id参数和一个DeviceDataDto对象作为请求参数，返回void")
    public BaseResponse updateDeviceData(@PathVariable @ApiParam(value = "设备数据ID", required = true) Long id, @RequestBody @ApiParam(value = "设备数据", required = true) DeviceDataDto deviceDataDto) {
        deviceDataService.updateDeviceData(id, deviceDataDto);
        return ResultUtils.success(true);
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "删除设备数据", notes = "接收一个id参数作为请求参数，返回void")
    public BaseResponse deleteDeviceData(@PathVariable @ApiParam(value = "设备数据ID", required = true) Long id) {
        deviceDataService.deleteDeviceData(id);
        return ResultUtils.success(true);
    }

    @GetMapping("/get-page")
    @ApiOperation(value = "获取设备数据分页结果", notes = "接收包含分页信息的请求参数，返回一个包含分页数据的Page<DeviceDataDto>对象")
    public BaseResponse<PageResponse<DeviceDataVo>> getDeviceDataPage(
            @ApiParam(value = "页码", required = true) @RequestParam("pageNum") Integer pageNum,
            @ApiParam(value = "每页大小", required = true) @RequestParam("pageSize") Integer pageSize,
            @ApiParam(value = "设备名称") @RequestParam(value = "deviceName", required = false) String deviceName,
            @ApiParam(value = "接入位置") @RequestParam(value = "accessLocation", required = false) String accessLocation,
            @ApiParam(value = "位置类型") @RequestParam(value = "accessLocation", required = false) Integer locationType,
            @ApiParam(value = "功能ID") @RequestParam(value = "functionId", required = false) String functionId,
            @ApiParam(value = "开始时间")  @RequestParam(required = false) Long startTime,
            @ApiParam(value = "结束时间")  @RequestParam(required = false) Long endTime,
            @ApiParam(value = "状态 0 正常 1 异常 2待处理 3已处理")  @RequestParam(required = false) Integer status) {
        return ResultUtils.success(deviceDataService.getDeviceDataPage(pageNum, pageSize, status, deviceName, accessLocation, locationType, functionId, ObjectUtil.isEmpty(startTime)? null : LocalDateTimeUtil.of(startTime), ObjectUtil.isEmpty(endTime)? null : LocalDateTimeUtil.of(endTime)));
    }


    @GetMapping("/data")
    @ApiOperation(value = "根据设备名获取最近一次上报数据")
    public BaseResponse<List<DeviceData>> getNewData(String name) throws JsonProcessingException {
        LambdaUpdateWrapper<Device> deviceLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        deviceLambdaUpdateWrapper.eq(Device::getDeviceName,name);
        Device device = deviceService.getBaseMapper().selectOne(deviceLambdaUpdateWrapper);

        Object o =  redisTemplate.opsForHash().get(Constants.DEVICE_LASTDATA_CACHE_KEY,device.getDeviceId());
        String json = (String)o;
        // 解析 JSON 字符串
        List<DeviceData> list = JSONUtil.toList(json, DeviceData.class);


        return ResultUtils.success(list,"数据返回成功");
    }

}
